package com.lxmes.device.service.impl;

import com.lxmes.common.annotation.DataScope;
import com.lxmes.common.config.RuoYiConfig;
import com.lxmes.common.core.domain.entity.SysUser;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.Sample;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.device.domain.DeviceFailureRepair;
import com.lxmes.device.domain.DeviceFailureReport;
import com.lxmes.device.mapper.DeviceFailureRepairMapper;
import com.lxmes.device.mapper.DeviceFailureReportMapper;
import com.lxmes.device.service.IDeviceFailureRepairService;
import com.lxmes.device.utils.WaterMarkUtils;
import com.lxmes.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 * 设备故障维修单Service业务层处理
 *
 * @author 张志煜
 * @date 2022-04-20
 */
@Service
public class DeviceFailureRepairServiceImpl implements IDeviceFailureRepairService
{
    @Autowired
    private DeviceFailureRepairMapper deviceFailureRepairMapper;
    @Autowired
    private DeviceFailureReportMapper deviceFailureReportMapper;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 查询设备故障维修单
     *
     * @param id 设备故障维修单主键
     * @return 设备故障维修单
     */
    @Override
    public DeviceFailureRepair selectDeviceFailureRepairById(Long id)
    {
        return deviceFailureRepairMapper.selectDeviceFailureRepairById(id);
    }

    @Override
    public DeviceFailureRepair selectDeviceFailureRepairByReportId(String reportId) {
        return deviceFailureRepairMapper.selectDeviceFailureRepairByReportId(reportId);
    }

    /**
     * 查询设备故障维修单列表
     *
     * @param deviceFailureRepair 设备故障维修单
     * @return 设备故障维修单
     */
    @Override
    @DataScope(deptAlias = "defr", userAlias = "defr")
    public List<DeviceFailureRepair> selectDeviceFailureRepairList(DeviceFailureRepair deviceFailureRepair)
    {
        return deviceFailureRepairMapper.selectDeviceFailureRepairList(deviceFailureRepair);
    }

    /**
     * 新增设备故障维修单
     *
     * @param deviceFailureRepair 设备故障维修单
     * @return 结果
     */
    @Override
    public int insertDeviceFailureRepair(DeviceFailureRepair deviceFailureRepair)
    {
        deviceFailureRepair.setCreateTime(DateUtils.getNowDate());
        return deviceFailureRepairMapper.insertDeviceFailureRepair(deviceFailureRepair);
    }

    /**
     * 修改设备故障维修单
     *
     * @param deviceFailureRepair 设备故障维修单
     * @return 结果
     */
    @Override
    public int updateDeviceFailureRepair(DeviceFailureRepair deviceFailureRepair)
    {
        deviceFailureRepair.setUpdateTime(DateUtils.getNowDate());
        return deviceFailureRepairMapper.updateDeviceFailureRepair(deviceFailureRepair);
    }

    @Override
    @Transactional
    public int updateApiDeviceFailureRepair(DeviceFailureRepair deviceFailureRepair) throws Exception {
        Long majorId=deviceFailureRepair.getMajorId();
        Long userId=SecurityUtils.getUserId();
        deviceFailureRepair.setEndTime(DateUtils.getTime());
        if(majorId.longValue()!=userId.longValue()){
            throw new ServiceException("当前用户不是主修人不能提交维修单！");
        }
        if(StringUtils.isNotNull(deviceFailureRepair.getRepairImg())){
            String path[]= deviceFailureRepair.getRepairImg().split(",");
            for (int i = 0; i <path.length ; i++) {
                WaterMarkUtils.resizeImage(path[i],360,600);
                WaterMarkUtils.creat(path[i],"主修人："+deviceFailureRepair.getMajor(),"维修时间："+deviceFailureRepair.getEndTime());
                WaterMarkUtils.commPressPicCycle(path[i],0.8);
            }
        }
        if(StringUtils.isNotBlank(deviceFailureRepair.getIsShutdown())){
            if(StringUtils.equals("是",deviceFailureRepair.getIsShutdown())){
                DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportByReportId(deviceFailureRepair.getReportId());
                String min=DateUtils.getDifferenceMin(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,deviceFailureRepair.getEndTime()),DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,report.getOccurrenceTime()));
                deviceFailureRepair.setShutdownDuration(min);
            }
        }
        String min=DateUtils.getDifferenceMin(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,deviceFailureRepair.getEndTime()),DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,deviceFailureRepair.getStartTime()));
        deviceFailureRepair.setRepairTimeuse(min);
        String reportId=deviceFailureRepair.getReportId();
        DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
        report.setFaultProgress("3");
         deviceFailureRepairMapper.updateApiDeviceFailureRepair(deviceFailureRepair);
         deviceFailureReportMapper.updateDeviceFailureReport(report);
        if(RuoYiConfig.isIsSendSms()) {
            SysUser u = new SysUser();
            u.setDeptId(report.getDeptId());
            List<SysUser> uList = sysUserService.selectUserAdmin(u);
            for (SysUser o : uList) {
                if (StringUtils.isNotBlank(o.getPhonenumber())) {
                    Sample.sendSms(o.getPhonenumber(), reportId, "SMS_249850174");
                }
            }
        }
        return 1;
    }

    /**
     * 批量删除设备故障维修单
     *
     * @param ids 需要删除的设备故障维修单主键
     * @return 结果
     */
    @Override
    public int deleteDeviceFailureRepairByIds(Long[] ids)
    {
        return deviceFailureRepairMapper.deleteDeviceFailureRepairByIds(ids);
    }

    @Override
    @Transactional
    public int cancelReport(String reportId) {
        DeviceFailureRepair repair =deviceFailureRepairMapper.selectDeviceFailureRepairByReportId(reportId);
        if(StringUtils.isNull(deviceFailureRepairMapper)){
            throw new ServiceException("未找到维修单撤销失败！");
        }
        DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
        if(StringUtils.equals(report.getFaultProgress(),"4")){
            throw new ServiceException("此报修单已完成维修不能撤销");
        }
        report.setFaultProgress("0");
        report.setRemark("已撤单-原主修人"+report.getMajor());
        deviceFailureRepairMapper.deleteDeviceFailureRepairByReportId(reportId);
        return  deviceFailureReportMapper.updateDeviceFailureReport(report);
    }

    /**
     * 删除设备故障维修单信息
     *
     * @param id 设备故障维修单主键
     * @return 结果
     */
    @Override
    public int deleteDeviceFailureRepairById(Long id)
    {
        return deviceFailureRepairMapper.deleteDeviceFailureRepairById(id);
    }
    /**
     * 变更维修人员
     *
     * @param reportId 设备故障维修单主键
     * @param majorId 主修人ID
     * @param fzMajorId 辅修人
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDeviceFailureRepairJobSub(String reportId, Long majorId, Long[] fzMajorId) {
        DeviceFailureRepair repair =deviceFailureRepairMapper.selectDeviceFailureRepairByReportId(reportId);
        if(StringUtils.isNull(deviceFailureRepairMapper)){
            throw new ServiceException("未找到维修单变更失败！");
        }
        DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
        SysUser major = sysUserService.selectUserById(majorId);
        if(StringUtils.isNull(major)){
            throw new ServiceException("未找到主维修人"+majorId);
        }
        report.setMajor(major.getNickName());
        report.setMajorId(majorId);
        repair.setMajor(major.getNickName());
        repair.setMajorId(majorId);
        repair.setUserId(majorId);
        String fzMajorIds=" ";
        String fzMaJorNames=" ";
        for (int j = 0; j <fzMajorId.length ; j++) {
            if(fzMajorId[j].longValue() == majorId.longValue()){
                continue;
            }
            SysUser fzMajor = sysUserService.selectUserById(fzMajorId[j]);
            if(StringUtils.isNull(fzMajor)){
                continue;
            }else {
                fzMajorIds+=fzMajor.getUserId()+",";
                fzMaJorNames+=fzMajor.getNickName()+",";
            }
        }
        if(StringUtils.isNotBlank(fzMaJorNames)&&StringUtils.isNotBlank(fzMajorIds)){
            report.setFzMaJors(fzMaJorNames.substring(0,fzMaJorNames.length()-1));
            report.setFzMajorIds(fzMajorIds.substring(0,fzMajorIds.length()-1));
            repair.setFzMajors(fzMaJorNames.substring(0,fzMaJorNames.length()-1));
            repair.setFzMajorIds(fzMajorIds.substring(0,fzMajorIds.length()-1));
        }
        report.setRemark("变更主修人"+report.getMajor());
        repair.setRemark("变更主修人"+report.getMajor());
        deviceFailureReportMapper.updateDeviceFailureReport(report);
        deviceFailureRepairMapper.updateDeviceFailureRepair(repair);
        return 1;
    }
    /* 维修故障确认
     * @param reportId 保修单号
     * @param confirmImg 故障确认图片
     * @return 结果
     */
    @Override
    @Transactional
    public int apiUpdateConfirm(DeviceFailureRepair deviceFailureRepair) throws IOException {
        if(StringUtils.isNull(deviceFailureRepair)){
            if(StringUtils.isBlank(deviceFailureRepair.getReportId())||StringUtils.isBlank(deviceFailureRepair.getConfirmImg())){
                throw new ServiceException("故障确认无数据！");
            }
        }
        DeviceFailureRepair repair = deviceFailureRepairMapper.selectDeviceFailureRepairByReportId(deviceFailureRepair.getReportId());
        Long majorId=repair.getMajorId();
        Long userId=SecurityUtils.getUserId();
        if(majorId.longValue()!=userId.longValue()){
            throw new ServiceException("当前用户不是主修人不能确认故障单！");
        }
        String time=DateUtils.getTime();
        if(StringUtils.isNotNull(deviceFailureRepair.getConfirmImg())){
            String path[]= deviceFailureRepair.getConfirmImg().split(",");
            for (int i = 0; i <path.length ; i++) {
                WaterMarkUtils.resizeImage(path[i],360,600);
                WaterMarkUtils.creat(path[i],"故障确认人："+repair.getMajor(),"确认时间："+time);
                WaterMarkUtils.commPressPicCycle(path[i],0.8);

            }
        }
        repair.setIsConfirm("1");
        repair.setConfirmImg(deviceFailureRepair.getConfirmImg());
        repair.setConfirmTime(time);
        return deviceFailureRepairMapper.updateDeviceFailureRepair(repair);
    }

    @Override
    @Transactional
    public int updateApiStartRepair(String reportId) {
        DeviceFailureReport report = deviceFailureReportMapper.selectDeviceFailureReportByReportId(reportId);
        DeviceFailureRepair repair = deviceFailureRepairMapper.selectDeviceFailureRepairByReportId(reportId);
        report.setFaultProgress("2");
        repair.setFaultProgress("2");
        repair.setStartTime(DateUtils.getTime());
        deviceFailureReportMapper.updateDeviceFailureReport(report);
        deviceFailureRepairMapper.updateDeviceFailureRepair(repair);
        return 1;
    }

    /*手机端全部维修列表*/
    @Override
    @DataScope(deptAlias = "defr", userAlias = "defr")
    public List<DeviceFailureRepair> selectApiDeviceFailureRepairList(DeviceFailureRepair deviceFailureRepair) {

        return deviceFailureRepairMapper.selectApiDeviceFailureRepairList(deviceFailureRepair);
    }
    /**
     * 查询手机端设备故障待派单、待执行、维修中列表
     *
     * @param deviceFailureRepair 设备故障维修单
     * @return 设备故障维修单集合
     */
    @Override
    @DataScope(deptAlias = "dfr", userAlias = "dfr")
    public List<DeviceFailureRepair> selectApiDeviceFailureRepairProgressList(DeviceFailureRepair deviceFailureRepair) {
        return deviceFailureRepairMapper.selectApiDeviceFailureRepairProgressList(deviceFailureRepair);
    }
    //待派单、待执行、维修中、待验证数据统计
    @Override
    @DataScope(deptAlias = "dfr", userAlias = "dfr")
    public int selectApiDeviceFailureStatistics(DeviceFailureRepair deviceFailureRepair) {
        return deviceFailureRepairMapper.selectApiDeviceFailureStatistics(deviceFailureRepair);
    }
}
